<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Role;

class RoleController extends Controller
{
    public function index(Request $request){
        $paginate = $request->has('paginate') ? $request->paginate : 15;
        $role = Role::paginate($paginate);
        return json_encode([
            'code' => '1',
            'data' => $role
        ]);
    }

    //获取一个
    public function get(Request $request){
        if(!$request->has('id')){
            return json_encode([
                'code' => '0',
                'data' => '请输入ID'
            ]);
        }
        $id = $request->id;
        $role = Role::find($id);
        return json_encode([
            'code' => '1',
            'data' => $role
        ]);
    }

    //添加或者修改
    public function edit(Request $request){
        if(!$request->has('name') || !$request->has('menu_ids')){
            return json_encode([
                'code' => '0',
                'data' => '角色名称，菜单IDs不能为空！'
            ]);
        }
        if(!$request->has('id')){
            //add
            $role = new Role;
            $role->name = $request->name;
            $role->menu_ids = $request->menu_ids;
            $role->save();
        }else{
            $role = Role::find($request->id);
            if(!$role){
                return json_encode(['code'=>'0','data'=>'保存失败,ID不存在']);
            }
            $role->name = $request->name;
            $role->menu_ids = $request->menu_ids;
            $role->save();
        }
        return json_encode([
            'code' => '1',
            'data' => '保存成功'
        ]);
    }

    //删除
    public function del(Request $request){
        if(!$request->has('id')){
            return json_encode([
                'code' => '0',
                'data' => '请输入ID'
            ]);
        }
        $id = $request->id;
        Role::destroy($id);
        return json_encode([
            'code' => '1',
            'data' => '删除成功'
        ]);
    }
}
